<template>
  <a-row>
    <div class="total-table-container">
      <a-row>
        <a-table
          :columns="tableColumns"
          :data-source="tableDataLists"
          :scroll="{ x: 1200 }"
          :rowKey="
            (record, index) => {
              return index;
            }
          "
          :customRow="clickSingleRow"
          :loading="isLoading"
          :pagination="false"
          bordered
        >
        </a-table>
      </a-row>
    </div>
  </a-row>
</template>

<script>
import moment from "moment";
import api from "@/server/userConfig";
import { buildLinkSelect, getRoleId } from "@/unit/tool";
import { RepairResultType } from "@/unit/constantValue";
import { columns } from "./tableConfig";
import { AssignRules, FixDoneRules, FinishRules } from "./rulesConfig";
import ExportFile from "vue-json-excel";

function getRangeTime(value) {
  switch (value) {
    case 0:
      return [
        moment()
          .quarter(moment().quarter())
          .startOf("quarter"),
        moment()
          .quarter(moment().quarter())
          .endOf("quarter")
      ];
    case 1:
      return [
        moment()
          .quarter(moment().quarter() - 1)
          .startOf("quarter"),
        moment()
          .quarter(moment().quarter() - 1)
          .endOf("quarter")
      ];
    case 2:
      return [
        moment()
          .year(moment().year())
          .startOf("year"),
        moment()
          .year(moment().year())
          .endOf("year")
      ];
    case 3:
      return [
        moment()
          .year(moment().year() - 1)
          .startOf("year"),
        moment()
          .year(moment().year() - 1)
          .endOf("year")
      ];
    case 4:
      return [moment(), moment()];
    default:
      break;
  }
}

function buildJsonFields(lists) {
  let jsonFields = {};
  lists.forEach((item, index) => {
    if (item.dataIndex != "operateStatus") {
      jsonFields[item.title] = item.dataIndex;
    }
  });
  return jsonFields;
}

export default {
  name: "HistoryOrderTable",
  props: {
    searchData: Object
  },
  components: {
    ExportFile
  },
  data() {
    return {
      userName: "",
      role: "",
      compId: "",
      secondDepartment: "",
      tableColumns: columns,
      tableDataLists: [],
      isLoading: false
    };
  },
  computed: {},
  watch: {
    searchData: {
      immediate: true,
      handler: function(newVal, oldVal) {
        let _this = this;
        let { district, timeType, startTime, endTime } = newVal;
        // let rangeTime = getRangeTime(timeType);
        this.getAreaMoney({}, "tableDataLists");
      }
    }
  },
  created() {},
  mounted() {
    getRoleId(this);
  },
  methods: {
    // 获取片区统计
    async getAreaMoney(parames, key) {
      let _this = this;
      _this.isLoading = true;
      let { district, startTime, endTime } = _this.searchData;
      const res = await api.getAreaMoney({
        area: district,
        startTime: `${startTime} 00:00:00`,
        endTime: `${endTime} 23:59:59`
      });
      _this.isLoading = false;
      if (res.MsgCode !== 0) {
        return;
      }
      let { Data } = res;
      this[key] = Data;
      console.log(key, Data);
    },

    // 点击每一行的跳转;
    clickSingleRow(record, index) {
      let _this = this;
      return {
        on: {
          click: () => {
            // 实现跳转;
            // window.open(`/#/productRepairDetail?id=${record.repairId}`);
            let { area } = record;
            let { district, timeType, startTime, endTime } = this.searchData;
            this.$router.push({
              name: "areaStatisticsDetail",
              params: {
                mainArea: district,
                relatedArea: area,
                timeType,
                startTime,
                endTime
              }
            });
          }
        }
      };
    },
    // 获取需要导出的数据
    async getDownloadData() {
      let _this = this;
      if (_this.iconLoading == true) {
        return false;
      }
      let total = _this.paginationOpt.total;
      let pageSize = 300;
      let length = Math.ceil(total / pageSize);
      let newLists = [];
      _this.iconLoading = true;
      for (let i = 1; i <= length; i++) {
        let lists = await this.buildDownloadLists({
          pageNum: i,
          pageSize: pageSize
        });
        newLists.push(lists);
      }
      _this.iconLoading = false;
      return [].concat(...newLists);
    },

    async buildDownloadLists(parames) {
      let _this = this;
      let { pageNum, pageSize } = parames;
      let { isProcess, statusList, ...restparames } = _this.searchData;
      const res = await api.getAllRepair({
        pageNum,
        pageSize,
        username: isProcess ? _this.userName : "",
        statusList: statusList ? statusList.toString() : "",
        operateUsername: _this.userName,
        ...restparames
      });

      if (res.msgCode !== 0) {
        return;
      }

      let list = buildLists(res.data.rows);
      return list;

      function buildLists(lists) {
        return lists.map((item, index) => {
          try {
            let newItem = format(item);
            return newItem;
          } catch (e) {
            console.log(e);
          }
        });
      }

      function format(item) {
        if (item.repairNumber) {
          item.repairNumber = `'${item.repairNumber}'`;
        }
        if (item.status) {
          item.status = formatState(item.status);
        }
        return item;
      }

      function formatState(state) {
        switch (state) {
          case 2:
            return "返厂中";
          case 3:
            return "已收货";
          case 4:
            return "已指派";
          case 5:
            return "维修收货";
          case 6:
            return "维修中";
          case 8:
            return "维修完成";
          case 10:
            return "返修完成";
          case 11:
            return "维修中";
          default:
            break;
        }
      }
    }
  }
};
</script>

<style lang="css" scoped>
@import "./style.css";
.itemWrap {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  justify-content: flex-start;
  align-items: center;
}

.itemWrap > .label {
  min-width: 90px;
  font-size: 16px;
  font-family: Microsoft YaHei;
  font-weight: 400;
  color: #373737;
  text-align: right;
}

.itemWrap > .separator {
  padding: 0px 4px;
}

.itemWrap > .content {
  width: 100%;
  padding: 0px 1px;
}
</style>
